/**
 * APICategory
 * Created by yanjd on 2017/9/22.
 */

import {type, typeList} from '../type'
import Vue from 'vue'
const vm = new Vue()
let api = {}

const CLIENT_GAME = '1'
const MOBILE_GAME = '2'


/**
 * 获取游戏币单位
 * @param state
 * @param commit
 * @param rootState
 * @param params = {gameId}
 */
api[type.getGameUnit] = ({state, commit, rootState}, params) => {
  return rootState.axios.post(rootState.CONSTANTS.P30006 + 'category/getcurrencyunitbygameid', params).then(res => {
    return res.data.unit || ''
  })
}

/**
 * 获取游戏动态属性
 * @param state
 * @param commit
 * @param rootState
 * @param params = {mainGid, gameId, goodstypeId, isQuickRelease} mainGid为主站游戏id
 */
api[type.gameProperty] = ({state, commit, rootState}, params) => {
  return rootState.axios.get(rootState.CONSTANTS.APICategory + 'gamePropertyRelation/getAllPropertyRelation', {params:params}).then(res => {
    return res.data
  })
}

/**
 * 获取服务器列表
 * @param state
 * @param commit
 * @param params = {aid， gameId}
 * @returns {Promise}
 */
api.getGameServers = function ({state, commit, rootState}, params) {
  return new Promise((resolve, reject) => {
    let id = JSON.stringify(params)
    if (getFirstKey(state._game_server) && JSON.parse(getFirstKey(state._game_server)).gameId !== params.gameId) commit(typeList.clearGameServer)
    else if (state._game_server[id] && state._game_server[id].length) { // 缓存切换游戏需清理
      //console.log('缓存服务器列表', state._game_server.list.length)
      setTimeout(resolve(state._game_server[id]), 0)
      return
    }
    delete params.gameId
    rootState.axios.get(rootState.CONSTANTS.P30006 + '/mainMobileGame/getgameServer', {params}).then(res => {
      res = {list: res.data.data || [], id}
      resolve(res.list)
      commit(typeList.setGameServer, {k: res.id, d: res.list})
    }, () => {
      //console.error('服务器列表请求错误 (╯‵□′)╯︵┻━┻')
      resolve([])
    })
  })
}


/**
 * 获取游戏客户端
 * @param state
 * @param commit
 * @param params = {gameId, platformId}
 * @returns {Promise}
 */
api.getGameClients = function ({state, commit, rootState}, params) {
  return new Promise((resolve, reject) => {
    let id = JSON.stringify(params)
    if (getFirstKey(state._game_client) && JSON.parse(getFirstKey(state._game_client)).gameId !== params.gameId) commit(typeList.clearGameClient)
    else if (state._game_client[id] && state._game_client[id].length) { // 缓存切换游戏需清理
      console.log('缓存客户端列表', state._game_client[id].length)
      setTimeout(resolve(state._game_client[id]), 0)
      return
    }
    rootState.axios.get(rootState.CONSTANTS.P30006 + '/mainMobileGame/getgameareasbygameandplatform', {params}).then(res => {
      res = {list: res.data.data || [], id}
      resolve(res.list)
      commit(typeList.setGameClient, {k: res.id, d: res.list})
    }, () => {
      //console.error('客户端列表请求错误 (╯‵□′)╯︵┻━┻')
      resolve([])
    })
  })
}

/**
 * 获取游戏平台
 * @param state
 * @param commit
 * @param params {gameId}
 * @returns {Promise}
 */
api.getGamePlants = function ({state, commit, rootState}, params) {
  return new Promise((resolve, reject) => {
    let id = params.gameId
    if (state._game_platform.list.length && state._game_platform.id === id) {
      //console.log('获取平台列表：', state._game_platform.list.length)
      setTimeout(resolve(state._game_platform.list), 0)
      return
    }
    rootState.axios.get(rootState.CONSTANTS.APICategory + '/mainMobileGame/getplatforminfobygameid', {params}).then(res => {
      res = {list: res.data.data || [], id}
      resolve(res.list)
      commit(typeList.setGamePlatform, res)
    }, () => {
      //console.error('平台列表请求错误 (╯‵□′)╯︵┻━┻')
      resolve([])
    })
  })
}


/**
 * 获取游戏商品类型
 * @param state
 * @param commit
 * @param params = {gameId}
 * @returns {Promise}
 */
api.getGoodsTypes = function ({state, commit, rootState}, params) {
  return new Promise((resolve, reject) => {
    let id = params.gameId
    if (state._goods_types.list.length && state._goods_types.id === id) {
      //console.log('获取商品列表：', state._goods_types.list.length)
      setTimeout(resolve(state._goods_types.list), 0)
      return
    }
    var rootParams = rootState.CONSTANTS.APImCategory + 'category/searchgoodstypebygameid'
    rootState.axios.get(
      rootParams,
      {params}).then(res => {
      res = {list: res.data.goodsTypeList || [], id}
      resolve(res.list)
      commit(typeList.setGoodsTypes, res)
    }, () => {
      //console.error('手游商品列表请求错误 (╯‵□′)╯︵┻━┻')
      resolve([])
    })
  })
}

/**
 * 获取游戏列表
 * @param state
 * @param commit
 * @param fn  # 回调函数
 * @param params
 * {gameType: 1 | 2, pageIndex: 1, pageSize: 9999} 1端游 2是手游
 */
api.MG_GET_GAMES = function ({state, commit, rootState}, params) {
  return new Promise((resolve, reject) => {
    //console.log('获取游戏列表：', state._games[params.gameType])
    if (state._games[params.gameType] && state._games[params.gameType].length) {
      setTimeout(resolve(state._games[params.gameType]), 0)
      return
    }
    rootState.axios.post(rootState.CONSTANTS.P30006 + 'category/searchgamelistbytype',params).then(res => {
      resolve(res.data.data || [])
      commit(typeList.setGames, {k: params.gameType, d: res.data.data || []})
    }, () => {
      //console.error('手游游戏列表请求错误 (╯‵□′)╯︵┻━┻')
      resolve([])
    })
  })
}

/***
 * 获取游戏首拼列表
 * @param state
 * @param commit
 * @param rootState
 * @param params = {gameType： 1 | 2} 1端游 2手游
 * @returns {Promise}
 * @constructor
 */
api.MG_GET_GAMES_PY = function ({state, commit, rootState}, params) {
  return new Promise((resolve, reject) => {
    //console.log('获取游戏首拼：', state._game_py[params.gameType])
    if (state._game_py[params.gameType] && state._game_py[params.gameType].length) {
      setTimeout(resolve(state._game_py[params.gameType]), 0)
      return
    }
    rootState.axios.post(rootState.CONSTANTS.P30006 + 'category/getgamepy', params).then(res => {
      resolve(res.data.py || [])
      commit(typeList.setGamePy, {k: params.gameType, d: res.data.py || []})
    }, () => {
      //console.error('游戏首拼请求错误 (╯‵□′)╯︵┻━┻')
      resolve([])
    })
  })
}

/***
 * 获取“我要卖”手游游戏列表
 * @param state
 * @param commit
 * @param rootState
 * @param params = {gameType(游戏类型), pageIndex, pageSize, pyfirst(不传则是返回热度)}
 * @returns {Promise}
 * @constructor
 */
api.MG_GET_GAMES_NEW = function ({state, commit, rootState}, params) {

  const gameType = params.gameType;
  const page = params.page;
  const first_py = params.first_py;

  var isNewlist = {};
  isNewlist.page = params.page;
  isNewlist.pageCount = params.pageCount;
  isNewlist.tableName="category";
  isNewlist.accurateMap = {
    "game_type": [gameType+""],
    "is_hot":["1"],
    "first_py":[first_py+""],
    // "is_publish_enabled":["true"]
  }
  isNewlist.sortMap={
    "popular_sort":"-"
  }
  if(first_py=="HOT"){
    delete isNewlist.accurateMap.first_py
  }else{
    delete isNewlist.accurateMap.is_hot
  }
  if (gameType === MOBILE_GAME) { // 手游
    // delete params.gameType
    return new Promise((resolve, reject) => {
      // if (!params.pyfirst) {
        //console.log('获取我要卖手游列表-热门：', state._sell_games['hot'])
        // if (state._sell_games['hot'] && state._sell_games['hot'].length) {
        //   setTimeout(resolve(state._sell_games['hot']), 0)
        //   return
        // }
        vm.$http.post(vm.$CONSTANTS.P30006 + 'goodsSearch/goodsSearchList', isNewlist).then((res)=>{

          // resolve(res.data.categoryList || []);
          if(res.data && res.data.responseStatus.code == "00" && res.data.result){
            resolve(JSON.parse(res.data.result).items || []);
            commit(typeList.setSellGames, {k: first_py, d: JSON.parse(res.data.result).items || []})
          }

        })
        // rootState.axios.get(rootState.CONSTANTS.APICategory + 'category/searchsygamelistbyhot', {params}).then(res => {
        //   resolve(res.data.categoryList || [])
        //   commit(typeList.setSellGames, {k: 'hot', d: res.data.categoryList || []})
        // }, () => {
        //   //console.error('手游我要卖游戏列表请求错误 (╯‵□′)╯︵┻━┻')
        //   resolve([])
        // })
      // } else {
      //   //console.log('获取我要卖手游列表-首字母' + params.pyfirst + ':', state._sell_games[params.pyfirst])
      //   if (state._sell_games[params.pyfirst] && state._sell_games[params.pyfirst].length) {
      //     setTimeout(resolve(_cutList(state._sell_games[params.pyfirst], pageIndex, pageSize)), 0)
      //     return
      //   }
      //   rootState.axios.get(rootState.CONSTANTS.APICategory + 'category/searchallsygamelist', {params}).then(res => {
      //     resolve(_cutList(res.data.categoryList || [], pageIndex, pageSize))
      //     commit(typeList.setSellGames, {k: params.pyfirst, d: res.data.categoryList || []})
      //   }, () => {
      //     //console.error('手游我要卖游戏列表请求错误 (╯‵□′)╯︵┻━┻')
      //     resolve([])
      //   })
      // }
    })
  }
  return new Promise((resolve, reject) => {
    // const pyfirst = params.pyfirst
    // delete params.pyfirst
    // //console.log('获取游戏列表：', state._games[params.gameType])
    // if (state._games[params.gameType] && state._games[params.gameType].length) {
    //   setTimeout(() => {
    //     resolve(_cutList(state._games[params.gameType].filter(gameItem => {
    //       return !pyfirst ? true : gameItem.pyfirst.toLowerCase() === pyfirst.toLowerCase()
    //     }), pageIndex, pageSize))
    //   }, 1)
    //   return
    // }
    params.page = page// 热门游戏前端限死
    isNewlist.sortMap={
      "create_time":"+",
      "popular_sort":"-"
    }
    vm.$http.post(vm.$CONSTANTS.P30006 + 'goodsSearch/goodsSearchList', isNewlist).then((res)=>{
        //let categoryList = res.data.categoryList || []
      if(res.data && res.data.responseStatus.code == "00" && res.data.result){

      }
      resolve(JSON.parse(res.data.result).items || []);
      commit(typeList.setGames, {k: params.gameType, d: JSON.parse(res.data.result).items || []})
    })
    // rootState.axios.get(rootState.CONSTANTS.P30006 + 'category/searchgamelistbytype', {params}).then(res => {
    //   let categoryList = res.data.categoryList || []
    //   resolve(_cutList(categoryList.filter(gameItem => {
    //     return !pyfirst ? true : gameItem.pyfirst.toLowerCase() === pyfirst.toLowerCase()
    //   }), pageIndex, pageSize))
    //   commit(typeList.setGames, {k: params.gameType, d: res.data.categoryList || []})
    // }, () => {
    //   //console.error('手游游戏列表请求错误 (╯‵□′)╯︵┻━┻')
    //   resolve([])
    // })
  })
}

/**
 * 搜索服务器接口
 * @param state
 * @param commit
 * @param rootState
 * @param params = {searchStr, gameId, platformId}
 */
api[type.searchServer] = ({state, commit, rootState}, params) => {
  return rootState.axios.get(rootState.CONSTANTS.APICategory + 'mainMobileGame/searchServerByName', {params}).then(res => {
    return res.data.data || []
  })
}

/**
 * 获取交易说明接口
 * @param state
 * @param commit
 * @param rootState
 * @param params = {gameId, goodsType}
 */
api[type.getTradeDescription] = ({state, commit, rootState}, params) => {
  return rootState.axios.get(rootState.CONSTANTS.APICategory + 'goodsTypeGameService/selectTradeDescription', {params}).then(res => {
    return res.data.tradeDescription || ''
  })
}

/**
 * 精准筛选接口
 * @param state
 * @param commit
 * @param rootState
 * @param params
 * @returns {Promise} {goodsTypeId: 游戏类型 2手游， gameName: 游戏名, goodsType: '游戏类型'}
 */
api.getFilterInner = function ({state, commit, rootState}, params) {
  // params = {goodsTypeId: 2, gameName: '地下城与勇士'}
  let goodsType = params.goodsType
  delete params.goodsType
  if (goodsType === 2)
    return rootState.axios.post(rootState.CONSTANTS.P30006 + 'gamePropertyRelation/queryFilterProperty', params).then(({data}) => {
      return data.gamePropertyRelationAllEOList || []
    }, () => {
      console.error('默认筛选请求错误 (╯‵□′)╯︵┻━┻')
      return []
    })
  else return new Promise((resolve, reject) => {
    resolve([{
        "displayName": "价格范围",
        "goodsTypeName": "游戏帐号",
        "propertyName": "价格范围",
        "isRequired": false,
        "isRelease": false,
        "gtrEnabled": false,
        "isDynamic": false,
        "isFilter": true,
        "filterSort": 91,
        "filterControlType": 5,
        "filterAlyField": "price",
        "filterType": 3,
        "subEOList": [
          {
            "id": 9818,
            "superId": 9952,
            "propertyName": "不限",
            "filterValue": "-",
            "isFilter": true,
            "filterSort": 1,
            "isQuickFilter": false,
            "filterAlyField": "price"
          },
          {
            "id": 9819,
            "superId": 9952,
            "propertyName": "50元以下",
            "filterValue": "1-49",
            "isFilter": true,
            "filterSort": 2,
            "isQuickFilter": false,
            "filterAlyField": "price"
          },
          {
            "id": 9820,
            "superId": 9952,
            "propertyName": "50-100元",
            "filterValue": "50-100",
            "isFilter": true,
            "filterSort": 3,
            "isQuickFilter": false,
            "filterAlyField": "price"
          },
          {
            "id": 9821,
            "superId": 9952,
            "propertyName": "100-500元",
            "filterValue": "100-500",
            "isFilter": true,
            "filterSort": 4,
            "isQuickFilter": false,
            "filterAlyField": "price"
          },
          {
            "id": 9822,
            "superId": 9952,
            "propertyName": "500-1000元",
            "filterValue": "500-1000",
            "isFilter": true,
            "filterSort": 5,
            "isQuickFilter": false,
            "filterAlyField": "price"
          },
          {
            "id": 9823,
            "superId": 9952,
            "propertyName": "1000元以上",
            "filterValue": "1000-",
            "isFilter": true,
            "filterSort": 6,
            "isQuickFilter": false,
            "filterAlyField": "price"
          }
        ],
        "isQuickFilter": false,
        "groupType": 0
      }
    ])
  })
}

/**
 * 精准筛选接口2
 * @param state
 * @param commit
 * @param rootState
 * @param params
 * @returns {Promise} {goodsTypeId: 游戏类型 2手游， gameName: 游戏名, goodsType: '游戏类型'}
 */
api.getFilterInner2 = function ({state, commit, rootState}, params) {
  // params = {goodsTypeId: 2, gameName: '地下城与勇士'}
  let goodsType = params.goodsTypeId
  delete params.goodsType
  if (goodsType === 2)
    return rootState.axios.get(rootState.CONSTANTS.APIMGSearch + 'syFilterProperty/queryFilterProperty', {params}).then(({data}) => {
      return data.syPropertyEOList || []
    }, () => {
      console.error('默认筛选请求错误 (╯‵□′)╯︵┻━┻')
      return []
    })
  else return new Promise((resolve, reject) => {
    resolve([
      {
        "id": 47456,
        "gameId": "8753691843024639bc5313fc007f730c",
        "gameName": "阴阳师",
        "goodsTypeId": "2",
        "goodsTypeName": "游戏帐号",
        "propertyName": "价格区间",
        "isRequired": false,
        "isFilter": true,
        "filterSort": 3,
        "filterControlType": 5,
        "mainFilterField": "price",
        "filterType": 3,
        "isQuickFilter": false,
        "groupType": 0,
        "subEOList": [{
            "id": 120024,
            "superId": 47456,
            "propertyName": "不限",
            "filterValue": "-",
            "isFilter": true,
            "filterSort": 1,
            "isQuickFilter": false,
            "mainFilterField": "price",
            "subCategory": ""
        }, {
            "id": 120025,
            "superId": 47456,
            "propertyName": "50元以下",
            "filterValue": "1-50",
            "isFilter": true,
            "filterSort": 2,
            "isQuickFilter": false,
            "mainFilterField": "price",
            "subCategory": ""
        }, {
            "id": 120026,
            "superId": 47456,
            "propertyName": "50-100元",
            "filterValue": "50-100",
            "isFilter": true,
            "filterSort": 3,
            "isQuickFilter": false,
            "mainFilterField": "price",
            "subCategory": ""
        }, {
            "id": 120027,
            "superId": 47456,
            "propertyName": "100-500元",
            "filterValue": "100-500",
            "isFilter": true,
            "filterSort": 4,
            "isQuickFilter": false,
            "mainFilterField": "price",
            "subCategory": ""
        }, {
            "id": 120028,
            "superId": 47456,
            "propertyName": "500-1000元",
            "filterValue": "500-1000",
            "isFilter": true,
            "filterSort": 5,
            "isQuickFilter": false,
            "mainFilterField": "price",
            "subCategory": ""
        }, {
            "id": 120029,
            "superId": 47456,
            "propertyName": "1000元以上",
            "filterValue": "1000-",
            "isFilter": true,
            "filterSort": 6,
            "isQuickFilter": false,
            "mainFilterField": "price",
            "subCategory": ""
        }]
    }
    ])
  })
}

/**
 * 快捷筛选接口
 * @param state
 * @param commit
 * @param rootState
 * @param params
 * @returns {Promise}
 */
api.getFilterOuter = function ({state, commit, rootState}, params) {
  return new Promise((resolve, reject) => {
    rootState.axios.post(rootState.CONSTANTS.P30006 + 'gamePropertyRelation/queryRapidFilterProperty', params).then(({data}) => {
      resolve(data.gamePropertyQuickVOList || [])
    }, () => {
      console.error('快捷筛选请求错误 (╯‵□′)╯︵┻━┻')
      resolve([])
    })
  })
}

function _cutList(list, pageIndex, pageCount) {
  let arr = []
  for (let i = (pageIndex - 1) * pageCount; i < Math.min(pageIndex * pageCount, list.length); i++) {
    arr.push(list[i])
  }
  return arr
}

function getFirstKey(obj) {
  for (let key in obj) {
    return key
  }
  return null
}

export default {
  ...api
}
